<template>
  <div>
    <!-- 面包导航区 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="#">商品管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>添加商品 </el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 提示区域 -->
      <el-alert :closable="false" title="添加商品" type="info" center>
      </el-alert>

      <!-- 步骤区域 -->
      <el-steps
        align-center
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tabs -->
      <el-form
        :model="addForm"
        :rules="addFormrules"
        ref="addFormref"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          @tab-click="tabonclick"
          :before-leave="leave"
          :tab-position="'left'"
          v-model="activeIndex"
        >
          <!-- 第一个页面 基本信息 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 第二个页面 动态信息 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTableDate"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="item2"
                  v-for="(item2, index) in item.attr_vals"
                  :key="index"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTableDate"
              :key="item.attr_id"
            >
              <el-input :value="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 第三个页面 商品图片 -->
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handSendSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <!-- 第四页面 商品内容  -->
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!-- 终极添加商品 -->
           <el-button @click="add" class="send" type="primary">添加商品</el-button>
          </el-tab-pane>

          
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览 -->
    <el-dialog
      title="有bug 缩略图请求时候 为什么不带token 我已经加在：headers里了，这很讨厌噢"
      :visible.sync="showpreview"
      width="50%"
    >
      <img :src="previewPath" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {



  data() {
    return {
      //当前哪个页面
      activeIndex: "0",

      //添加的商品的date
      addForm: {
        goods_name: "",
        goods_price: "",
        goods_number: "",
        goods_weight: "",
        //商品所属的 分类数组
        goods_cat: [],
        //图片数组
        pics: [],
        //商品介绍
        goods_introduce:'',
        //参数 动态或者静态
        attrs:[]
      },
      //规则
      addFormrules: {
        goods_name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
      },

      //所有商品列表 级联用
      cateList: [],
      //级联 节点展示关系
      cateProps: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },

      //动态参数页面数据
      manyTableDate: [],
      //静态参数页面数据
      onlyTableDate: [],

      //上传图片的地址
      uploadUrl: "http://www.ysqorz.top:8888/api/private/v1/upload",
      //上传图片 请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      //预览图片路径
      previewPath: "",
      //展示预览图片dialog flag
      showpreview: false,
    };
  },
  methods: {
    //获取所有商品列表 级联用
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200)
        return this.$message.error("获取所有商品列表失败");
      this.cateList = res.data;
    },
    //级联变化
    handleChange() {
      //console.log(this.addForm.goods_cat);
    },

    //离开标签页触发
    leave(newtab, oldtab) {
      if (oldtab === "0" && this.addForm.goods_cat.length !== 3) {
        this.$message.error("你没有填完表格");
        return false;
      }
    },
    //当标签页被点击时候触发
    async tabonclick() {
      //去 动态参数 页面时候加载 第一个页面选中的
      //商品所在的分类的 动态参数
      if (this.activeIndex === "1") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: "many",
            },
          }
        );
        console.log(res.data);
        //attr_vals里面的字符串变成数组
        res.data.forEach((item) => {
          item.attr_vals.length === 0
            ? (item.attr_vals = [])
            : (item.attr_vals = item.attr_vals.split(" "));
        });
        this.manyTableDate = res.data;
      }
      // 判断是不是去第二个页面
      if (this.activeIndex === "2") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: "only",
            },
          }
        );
        if (res.meta.status !== 200)
          return this.$message.error("请求静态参数失败");
        console.log(res.data);
        this.onlyTableDate = res.data;
      }
    },

    //点击图片查看预览
    handlePreview(file) {
      this.previewPath = file.response.data.url.substring(22);
      this.previewPath =
        "http://www.ysqorz.top:8888/api/private/v1/" + this.previewPath;
      console.log(this.previewPath);

      this.showpreview = true;
    },
    //图片移除
    handleRemove(file) {
      const filePath = file.response.data.tmp_path;
      console.log(filePath);

      const i = this.addForm.pics.findIndex((x) => x.pic === filePath);
      this.addForm.pics.splice(i, 1);
    },
    //图片上传到服务器缓存成功 加入到添加服务器信息总
    handSendSuccess(response) {
      const picInfo = {
        pic: response.data.tmp_path,
      };
      this.addForm.pics.push(picInfo);
      console.log(this.addForm);
    },
    //添加商品那
    async add(){
      //拷贝一份addForm
      const form = _.cloneDeep(this.addForm)
      form.goods_cat =form.goods_cat.join(',')

      // 处理动态参数
      this.manyTableDate.forEach(item=>{
        const newinfo ={
          attr_id:item.attr_id,
          attr_value:item.attr_vals.join(' ')
        }
        this.addForm.attrs.push(newinfo)
      })
      
      // 处理静态属性
      this.onlyTableDate.forEach(item=>{
        const newinfo ={
          attr_id:item.attr_id,
          attr_value:item.attr_vals
        }
        this.addForm.attrs.push(newinfo)
      })
      form.attrs= this.addForm.attrs
      console.log(form);
      
      const {data:res}=await this.$http.post('goods',form)
      // console.log(res);
      if(res.meta.status!==201)return this.$message.error('添加失败')
      this.$message.success('添加成功')
      this.$router.push('/goods')
      
    }
  },
  created() {
    this.getCateList();
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2];
      }
      return null;
    },
  },
};
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0;
}
.send{
  margin-top: 15px;
}
</style>